package com.xwd.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName BaseDao
 * @Description: com.com.xwd.dao
 * @Auther: xiwd
 * @Date: 2022/2/7 - 02 - 07 - 19:06
 * @version: 1.0
 */
public abstract class BaseDao extends ConnectionPool {
    //methods
    public static List baseQuery(Class clazz,String sql,Object ...args){
        List list=null;
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        //数据库操作
        try {
            //获取数据库连接
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            //设置查询参数
            for (int i = 0; i < args.length; i++) {
                statement.setObject(i+1,args[i]);
            }
            //执行SQL查询
            resultSet = statement.executeQuery();
            //实例化集合
            list=new ArrayList();
            //解析结果集
            while (resultSet.next()) {
                //通过反射创建对象
                Object newInstance = clazz.newInstance();
                //通过反射获取属性字段
                Field[] declaredFields = clazz.getDeclaredFields();
                int index=1;
                if (null!=declaredFields){
                    for (Field declaredField : declaredFields) {
                        //如果为static字段，就直接进入下一次循环
                        if (Modifier.isStatic(declaredField.getModifiers()))
                            continue;
                        //非static字段，进行解析
                        //获取字段名称
                        String name = declaredField.getName();
                        //获取setter方法
                        String setMethodName = getSetterByFiledNmae(name);
                        //通过反射获取setter方法
                        Method declaredMethod = clazz.getDeclaredMethod(setMethodName, declaredField.getType());
                        //System.out.println("setMethodName:"+setMethodName+"\t"+"ParamType:"+declaredField.getType().getName());
                        //调用gsetter方法
                        declaredMethod.invoke(newInstance,resultSet.getObject(index));
                        index++;
                    }
                    //System.out.println(newInstance.toString());
                    //将封装好的newInstance放入list中
                    list.add(newInstance);
                }
            }
            return list;
        }  catch (Exception e){
            e.printStackTrace();
            return list;
        }
    }

    private static String getSetterByFiledNmae(String fieldName) {
        if (null==fieldName||"".equals(fieldName))
            return null;
        return "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
    }
}
